
estimation_data <-
  estimation_data %>%
  mutate(rank_group = case_when(party_national_rank > 5 ~ "Low Performance Party",
                                party_national_rank < 6 ~ "High Performance Party"))






mod1 <- feols(avg_score_trust_elect ~ pre_post*validated_election_outcome, data = estimation_data %>% filter(rank_group == "Low Performance Party"), cluster = "ID")
mod2 <- feols(avg_score_trust_elect ~ pre_post*validated_election_outcome, data = estimation_data %>% filter(rank_group == "High Performance Party"), cluster = "ID")
mod7 <- feols(avg_score_democ_support ~ pre_post*validated_election_outcome, data = estimation_data %>% filter(rank_group == "Low Performance Party"), cluster = "ID")
mod8 <- feols(avg_score_democ_support ~ pre_post*validated_election_outcome, data = estimation_data %>% filter(rank_group == "High Performance Party"), cluster = "ID")


mods <- list(mod1, mod2, mod7, mod8)

table_df <-
  modelsummary(mods,
               stars = c("*" = 0.1, "**" = 0.05, "***" = 0.01),
               coef_map = c(
                 "pre_post" = "Post Election",
                 "validated_election_outcomeNot Elected" = "Outcome: Lost",
                 "pre_post:validated_election_outcomeNot Elected" = "Post x Lost"
               ),
               gof_map = c("nobs", "r.squared"),
               output = "data.frame"
  ) %>%
  mutate(term = ifelse(statistic == "std.error", "", term)) %>%
  select(-c(part, statistic)) %>%
  mutate_all(as.character)


# Append the new row to the table
latex_table <-
  table_df %>%
  kableExtra::kable("latex",
                    booktabs = T,
                    longtable = T,
                    escape = F,
                    cap = "\\label{tab:nat_party_perf}Main Analysis, by National Party Performance",
                    padding = 0,
                    col.names = linebreak(c("", "(1)", "(2)", "(3)", "(4)"), c("l", rep("c", 4))),
                    align = c("l", rep("c", 4)),
                    linesep = "") %>%
  kableExtra::row_spec(6, hline_after = T) %>%
  kableExtra::kable_styling(
    font_size = 9,
    latex_options = c("scale_down",
                      "hold_position",
                      "striped")) %>%
  kableExtra::add_header_above(
    header = c(
      " " = 1,
      "Low Vote %" = 1,
      "High Vote %" = 1,
      "Low Vote %" = 1,
      "High Vote %" = 1
    ),
    align = c("l", rep("c", 8))
  ) %>%
  kableExtra::add_header_above(
    header = c(
      " " = 1,
      "Trust in Elec." = 2,
      "Supp. for Dem." = 2
    ),
    align = c("l", rep("c", 4))
  )

cat("\\renewcommand{\\arraystretch}{0.9}\n", file = "./outputs/tables/table_a12.tex")
cat(latex_table, file = "./outputs/tables/table_a12.tex", append = TRUE)



